package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.Broadcaster;
import com.sh.d1.gameserver.model.MoveState;
import com.sh.d1.gameserver.model.User;
import com.sh.d1.gameserver.model.UserManager;
import com.sh.d1.gameserver.msg.GameMsgProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户移动指令处理器
 */
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(UserMoveToCmdHandler.class);

    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        if (null == ctx ||
            null == cmd) {
            return;
        }

        // 先拿到用户 Id
        int userId = ctx.getFromUserId();

        if (userId <= 0) {
            return;
        }

        // 获取英雄对象
        User existUser = UserManager.getByUserId(userId);
        if (null == existUser) {
            LOGGER.info("用户不存在, userId = {}", userId);
            return;
        }

        // 获取移动状态
        MoveState mvState = existUser.moveState;
        // 设置位置和时间
        mvState.fromPosX = cmd.getMoveFromPosX();
        mvState.fromPosY = cmd.getMoveFromPosY();
        mvState.toPosX = cmd.getMoveToPosX();
        mvState.toPosY = cmd.getMoveToPosY();
        mvState.startTime = System.currentTimeMillis();

        GameMsgProtocol.UserMoveToResult.Builder
            resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveFromPosX(mvState.fromPosX);
        resultBuilder.setMoveFromPosY(mvState.fromPosY);
        resultBuilder.setMoveToPosX(mvState.toPosX);
        resultBuilder.setMoveToPosY(mvState.toPosY);
        resultBuilder.setMoveStartTime(mvState.startTime);

        // 构建结果并发送
        GameMsgProtocol.UserMoveToResult newResult = resultBuilder.build();
        Broadcaster.broadcast(newResult);
    }
}
